import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/person/entity/area_entity.dart';
import 'package:shopping_group/modle/person/entity/soujianren_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';

class AddAddressBloc implements BlocBase {
  //  Stream来初始化地址的操作
  StreamController<Object> _initActionController = StreamController<Object>();
  //初始化动作
  StreamSink get initDate => _initActionController.sink;

  //  Stream来添加地址的操作
  StreamController<Object> _addAddressController = StreamController<Object>();
  StreamSink get addAddressDate => _addAddressController.sink;

  //  Stream来切换地址的操作
  StreamController<Object> _changeAddressController =
      StreamController<Object>();
  StreamSink get changeAddressDate => _changeAddressController.sink;

  AddAddressBloc() {
    _initActionController.stream.listen(initAddressData);
    _addAddressController.stream.listen(addAddressData);
    _changeAddressController.stream.listen(changeAddressData);
  }

  void addAddressData(data) {
    if (data is Map<String, dynamic>) {
      _addAddressTask(data);
    }
  }

  void changeAddressData(data) {
    if (data is Map<String, dynamic>) {}
  }

  void initAddressData(data) {
    if (data is String) {
      Future.wait([_areaList(), _initAddressTask(data)]);
    } else {
      _areaList();
    }
  }

  // 初始化地址
  Future _initAddressTask(id) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.closeAllLoading();
        BotToast.showText(text: '网络无法连接');
      } else {
        BotToast.showLoading();
        Map<String, dynamic> data = {};
        data['userId'] = BaseConstant.userId;
        data['val'] = id;
        HttpUtilAll.post(Apis.ONE_ADRESS_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          // 请求成功返回的数据
          if (null != result) {
            SouJianRenEntity entity = SouJianRenEntity.fromJson(result);

            eventBus.fire(OneSouJianRenEvent(entity));
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  // add地址数量
  Future _addAddressTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.closeAllLoading();
        BotToast.showText(text: '网络无法连接');
      } else {
        BotToast.showLoading();
        HttpUtilAll.post(Apis.ADD_ADRESS_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          // 请求成功返回的数据
          if (null != result) {
            BotToast.showText(text: '保存成功');
            eventBus.fire(SaveAddressEvent());
            SouJianRenEntity entity = SouJianRenEntity.fromJson(result);
            entity.souJianRenProvName = data['souJianRenProvName'];
            entity.souJianRenCityName = data['souJianRenCityName'];
            entity.souJianRenTownName = data['souJianRenTownName'];
            entity.souJianRenAddress = data['souJianRenAddress'];
            eventBus.fire(AddSouJianRenEvent(entity));
            RouteUtil.closeView();
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _areaList() async {
    if (!ObjectUtil.isEmptyList(BaseConstant.areaListEntity)) {
      return;
    }
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
        BotToast.closeAllLoading();
      } else {
        Map<String, dynamic> data = {};
        HttpUtilAll.post(Apis.ALL_AREA_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          BaseConstant.areaListEntity?.clear();
          // 请求成功返回的数据
          if (null != result) {
            List list = List.from(result);
            for (var item in list) {
              AreaEntity params = AreaEntity.fromJson(item);
              BaseConstant.areaListEntity.add(params);
            }
          }
          _initCity();
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  _initCity() {
    for (var item in BaseConstant.areaListEntity) {
      BaseConstant.provincesData[item.id] = item.name;
      Map<String, dynamic> twoPartenCities = {};
      if (!ObjectUtil.isEmptyList(item.areaChildList)) {
        for (var twoItem in item.areaChildList) {
          Map<String, dynamic> twocities = {};
          twocities['name'] = twoItem.name;
          // twocities['alpha'] =
          //     PinyinHelper.getFirstWordPinyin(twoItem.name).substring(0, 1);
          twoPartenCities[twoItem.id] = twocities;
          Map<String, dynamic> threePartenCities = {};
          if (!ObjectUtil.isEmptyList(twoItem.areaChildList)) {
            for (var threeItem in twoItem.areaChildList) {
              Map<String, dynamic> threeItemCities = {};
              threeItemCities['name'] = threeItem.name;
              // threeItemCities['alpha'] =
              //     PinyinHelper.getFirstWordPinyin(threeItem.name).substring(0, 1);
              threePartenCities[threeItem.id] = threeItemCities;
            }
          }
          BaseConstant.citysData[twoItem.id] = threePartenCities;
        }
      }
      BaseConstant.citysData[item.id] = twoPartenCities;
    }
  }

  @override
  void dispose() {
    _initActionController?.close();
    _addAddressController?.close();
    _changeAddressController?.close();
  }
}
